import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';
import { ControlWidget } from '@delon/form';
export class PV {
  _$id?: any;
  id?: string;
  propertyId?: string;
  sortId?: number;
  stateShow?: number;
  storeId?: number;
  value?: string;
  status?: number;
}
@Component({
  selector: 'sl-property-values',
  styles: [
    `
      ::ng-deep .cdk-drag-preview {
        display: table;
      }

      ::ng-deep .cdk-drag-placeholder {
        opacity: 0;
      }
    `,
  ],
  template: `
    <sf-item-wrap [id]="id" [schema]="schema" [ui]="ui" [showError]="showError" [error]="error" [showTitle]="schema.title">
      <button nz-button nzType="primary" (click)="addRow()">
        <i nz-icon nzType="plus" nzTheme="outline"></i>
        新增属性值
      </button>
      <nz-table
        #editRowTable
        nzBordered
        nzSize="small"
        [nzData]="listOfData"
        nzTableLayout="fixed"
        [nzFrontPagination]="false"
        [nzShowPagination]="false"
      >
        <thead>
          <tr>
            <th nzWidth="70px">排序</th>
            <th nzWidth="200px">属性值</th>
            <!-- <th nzWidth="200px">状态</th> -->
            <th>操作</th>
          </tr>
        </thead>
        <tbody cdkDropList (cdkDropListDropped)="drop($event)">
          <tr *ngFor="let data of editRowTable.data" cdkDrag>
            <ng-container *ngIf="!editCache[data._$id]?.edit; else editTemplate">
              <td>{{ data.sortId }}</td>
              <td>{{ data.value }}</td>
              <!-- <td>
                <span *ngIf="data.stateShow == 0 || data.status == 0">隐藏</span><span *ngIf="data.stateShow == 1 || data.status == 1">显示</span>
              </td> -->
              <td>
                <a (click)="startEdit(data._$id)">编辑</a>
                <nz-divider nzType="vertical"></nz-divider>
                <a (click)="deleteRow(data._$id)" class="text-danger">删除</a>
              </td>
            </ng-container>
            <ng-template #editTemplate>
              <td>
                <input type="text" nz-input [(ngModel)]="editCache[data._$id].data.sortId" />
              </td>
              <td>
                <input type="text" nz-input [(ngModel)]="editCache[data._$id].data.value" />
              </td>
              <!-- <td>
                <nz-radio-group
                  [(ngModel)]="editCache[data._$id].data.stateShow"
                  (ngModelChange)="changeRadio($event, editCache[data._$id].data)"
                  nzButtonStyle="solid"
                  nzSize="small"
                >
                  <label nz-radio-button [nzValue]="1">显示</label>
                  <label nz-radio-button [nzValue]="0">隐藏</label>
                </nz-radio-group>
              </td> -->
              <td>
                <a (click)="saveEdit(data._$id)" class="save">保存</a>
                <nz-divider nzType="vertical"></nz-divider>
                <a (click)="cancelEdit(data._$id)">取消</a>
              </td>
            </ng-template>
          </tr>
        </tbody>
      </nz-table>
    </sf-item-wrap>
  `,
  preserveWhitespaces: false,
})

// tslint:disable-next-line: component-class-suffix
export class PropertyValuesWidget extends ControlWidget {
  static readonly KEY = 'property-values';

  i = 0;
  editId: string | null = null;

  editCache: { [key: string]: { edit: boolean; data: PV } } = {};
  listOfData: PV[] = [];

  startEdit(id: string): void {
    this.editCache[id].edit = true;
    console.log(this.editCache[id]);
    // 开始编辑时禁止提交表单
    this.setValue(null);
  }

  changeRadio(e: any, item: any) {
    item.status = e;
    console.log(e, item);
  }

  cancelEdit(id: string): void {
    const index = this.listOfData.findIndex((item) => item._$id === id);
    this.editCache[id] = {
      data: { ...this.listOfData[index] },
      edit: false,
    };
    this.setValue(this.listOfData);
  }

  saveEdit(id: string): void {
    const index = this.listOfData.findIndex((item) => item._$id === id);
    Object.assign(this.listOfData[index], this.editCache[id].data);
    this.editCache[id].edit = false;
    this.setValue(this.listOfData);
  }

  updateEditCache(): void {
    this.listOfData.forEach((item) => {
      this.editCache[item._$id] = {
        edit: false,
        data: { ...item },
      };
    });
  }

  addRow(): void {
    this.i++;
    this.listOfData = [
      ...this.listOfData,
      {
        _$id: `${this.i}`,
        stateShow: 1,
      },
    ];
    this.updateEditCache();
    this.setValue(this.listOfData);
  }

  deleteRow(id: string): void {
    this.listOfData = this.listOfData.filter((d) => d._$id !== id);
    this.setValue(this.listOfData);
  }

  _change(value: any, index: number) {}

  reset(value: string) {}
  afterViewInit() {
    // 初始化数据
    this.listOfData = [];
    const formData: any = this.formProperty?.formData;
    if (formData) {
      const data = [...formData];
      for (let i = 0; i < data.length; i++) {
        this.i = i;
        this.listOfData.push({
          _$id: `${this.i}`,
          ...data[i],
        });
      }
      this.updateEditCache();
    }
  }

  drop(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.listOfData, event.previousIndex, event.currentIndex);
  }
}
